﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace B.S.BasicData.Api.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class UpLoadController : ControllerBase
    {
        [HttpPost]
        public async Task<IActionResult> Upload(IFormFile image)
        {
            // 检查是否有文件上传
            if (image == null || image.Length == 0)
                return BadRequest("没有上传图片");

            // 确保上传的是图片
            if (!IsImageFile(image))
                return BadRequest("上传的文件不是图片");

            // 生成保存路径
            var uploadsFolder = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "uploads");
            Directory.CreateDirectory(uploadsFolder);
            var fileName = Path.GetFileName(image.FileName);
            var filePath = Path.Combine(uploadsFolder, fileName);

            // 保存图片
            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                await image.CopyToAsync(stream);
            }

            // 返回图片的URL
            var imageUrl = $"{Request.Scheme}://{Request.Host}/uploads/{fileName}";
            return Ok(new { ImageUrl = imageUrl });
        }

        private bool IsImageFile(IFormFile file)
        {
            // 简单检查文件扩展名
            var extension = Path.GetExtension(file.FileName).ToLowerInvariant();
            return extension == ".jpg" || extension == ".jpeg" || extension == ".png" || extension == ".gif";
        }


    }
}
